#include "file.h"

// 文件打开
void My_File::open(const char * filename, const char * mode)
{
    this->fd = fopen(filename, mode);
}

// 文件是否打开
bool My_File::is_open()
{
    return this->fd != NULL;
}

// 文件关闭
void My_File::close()
{
    if (!this->is_open())
    {
        cout << "文件打开失败" << endl;
        return;
    }
    fclose(this->fd);
}

// 文件写入运算符重载
void My_File::operator<<(const char * buf)
{
    if (!this->is_open())
    {
        cout << "文件打开失败" << endl;
        return;
    }
    if (buf == NULL)
    {
        cout << "字符串为null" << endl;
        return;
    }
    fputs(buf,this->fd);
}
void My_File::operator<<(const string & str)
{
    if (!this->is_open())
    {
        cout << "文件打开失败" << endl;
        return;
    }
    fputs(str.c_str(),this->fd);
}
void My_File::operator<<(My_File & file)
{
    if (!file.is_open())
    {
        cout << "传入的文件打开失败" << endl;
        return;
    }
    char ch;
    while (EOF != (ch = fgetc(file.fd)))
    {
        fputc(ch,this->fd);
    }
}

// 文件读取运算符重载
void My_File::operator>>(char * buf)
{
    if (!this->is_open())
    {
        cout << "文件打开失败" << endl;
        return;
    }
    if (buf == NULL)
    {
        cout << "字符串为null" << endl;
        return;
    }
    char ch;
    int i = 0;
    while (EOF != (ch = fgetc(this->fd)))
    {
        buf[i++] = ch;
    }
    buf[i] = '\0';
}
void My_File::operator>>(string & str)
{
    if (!this->is_open())
    {
        cout << "文件打开失败" << endl;
        return;
    }
    char ch;
    while (EOF != (ch = fgetc(this->fd)))
    {
        str += ch;
    }
}  

    // 文件光标定位
void My_File::seek(long offset, int origin)
{
    if (!this->is_open())
    {
        cout << "文件打开失败" << endl;
        return;
    }
    fseek(this->fd,offset,origin);
}